/*
 * @Author: szx
 * @Date: 2022-05-04 14:48:01
 * @LastEditTime: 2022-05-04 15:07:21
 * @Description:
 * @FilePath: \leetcode\500-599\542\542.js
 */
/**
 * @param {number[][]} mat
 * @return {number[][]}
 */
/**
 * @param {number[][]} mat
 * @return {number[][]}
 */
var updateMatrix = function (mat) {
    const dirs = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1]
    ];
    const m = mat.length;
    const n = mat[0].length;
    const visited = new Array(m).fill(false).map(() => new Array(n).fill(false));
    const dist = new Array(m).fill(0).map(() => new Array(n).fill(0));
    const que = [];
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (mat[i][j] == 0) {
                que.push([i, j]);
                visited[i][j] = true;
            }
        }
    }
    while (que.length) {
        const [i, j] = que.shift();
        for (let dir of dirs) {
            const x = i + dir[0];
            const y = j + dir[1];
            if (x >= 0 && x < m && y >= 0 && y < n && !visited[x][y]) {
                dist[x][y] = dist[i][j] + 1;
                visited[x][y] = true;
                que.push([x, y]);
            }
        }
    }
    return dist;
};


var updateMatrix = function (mat) {
    const dirs = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1]
    ];
    const m = mat.length;
    const n = mat[0].length;
    const visited = new Array(m).fill(false).map(() => new Array(n).fill(false));
    const que = [];
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (mat[i][j] == 0) {
                que.push([i, j]);
                visited[i][j] = true;
            }
        }
    }
    while (que.length) {
        const [i, j] = que.shift();
        for (let dir of dirs) {
            const x = i + dir[0];
            const y = j + dir[1];
            if (x >= 0 && x < m && y >= 0 && y < n && !visited[x][y]) {
                mat[x][y] = mat[i][j] + 1;
                visited[x][y] = true;
                que.push([x, y]);
            }
        }
    }
    return mat;
};